import { createRouter, createWebHashHistory } from "vue-router";
import Login from "@/views/Login.vue";
import MainBox from "@/views/MainBox.vue";
import routesConfig from "./config";
import store from "../store/index";

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox,
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  if ((to.name === "login") | (to.name === "notfound")) {
    next();
  } else {
    if (localStorage.getItem("myToken")) {
      if (!store.state.isGetterToken) {
        ConfigRouter();
        store.commit("changeGetterToken", true);
        next({
          path: to.fullPath,
        });
      } else {
        next();
      }
    } else {
      next({
        path: "/login",
      });
    }
  }
});

const ConfigRouter = () => {
  routesConfig.forEach((item) => {
    router.addRoute("mainbox", item);
  });
};

export default router;
